<?php
namespace app\interceptors;

use rap\config\Config;
use rap\util\http\Http;
use rap\web\interceptor\Interceptor;
use rap\web\Request;
use rap\web\Response;

/**
 * 本地开发时的反向代理
 * User: jinghao@duohuo.net
 * Date: 18/9/4
 * Time: 下午5:51
 */
class RapInterceptors implements Interceptor {

    public function handler(Request $request, Response $response) {

        $proxys=Config::getFileConfig()["admin_proxy"];
        $path = $request->path();
        $to = explode('/', $path)[ 1 ];
        if (!key_exists($to, $proxys)) {
            return false;
        }

        $body = $request->body();
        $header = $request->header();
        $cookies = $request->cookie();
        $cookie_str = "";
        foreach ($cookies as $key => $value) {
            $cookie_str .= $key . "=" . $value . ";";
        }
        $header[ 'cookie' ] = $cookie_str;
        $response_proxy = Http::post($proxys[$to].$request->url(), $header, $body,10);
        $headers = $response_proxy->headers;
        foreach ($headers as $header => $value) {
            if(in_array(strtolower($header) ,['set-cookie'])){
                $response->header($header, $value);
            }
        }
        $response->contentType($headers['Content-Type']?$headers['Content-Type']:$headers['content-type']);
        $response->setContent($response_proxy->body);
        $response->send();
        return true;
    }

}